package Algorithm.DynamicPlanning;

public class Code02_MinPathSum {

    public static int minPathSum1(int[][] m){
        if (m == null || m.length == 0 || m[0] == null || m[0].length == 0){
            return 0;
        }
        int row = m.length;
        int col = m[0].length;
        int[][] dp = new int[row][col];
        dp[0][0] = m[0][0];
        for (int i = 1; i < row; i++){
            dp[i][0] = dp[i - 1][0] + m[i][0];
        }
        for (int j = 1; j < col; j++){
            dp[0][j] = dp[0][j - 1] + m[0][j];
        }
        for (int i = 1; i < row; i++) {
            for (int j = 1; j < col; j++){ // 左边和上面最小值+自己
                dp[i][j] = Math.min(dp[i][j - 1], dp[i - 1][j]) + m[i][j];
            }
        }
        return dp[row - 1][col - 1];
    }
    // 空间优化，变一维数组
    public static int minPathSum2(int[][] m) {
        if (m == null || m.length == 0 || m[0] == null || m[0].length == 0) {
            return 0;
        }
        int row = m.length;
        int col = m[0].length;
        int[] dp = new int[col];
        dp[0] = m[0][0];
        for (int j = 1; j < col; j++){
            dp[j] = dp[j - 1] + m[0][j];
        }
        // 左边和上面谁小取谁
        for (int i = 1; i < row; i++) {
            for (int j = 0; j < col; j++){ // 左边和上面最小值+自己
                if (j == 0){
                    dp[j] += m[i][j]; // 左边第一个只和上面有关
                } else{
                    dp[j] = Math.min(dp[j - 1], dp[j]) + m[i][j];
                }
            }
        }
        return dp[col - 1];
    }

    public static void main(String[] args) {
        int[][] m = { { 1, 3, 5, 9 }, { 8, 1, 3, 4 }, { 5, 0, 6, 1 },
                { 8, 8, 4, 0 } };
        System.out.println(minPathSum1(m));
        System.out.println(minPathSum2(m));
    }
}
